package com.baizan.daka.mvp.model

import android.util.Log
import com.baizan.daka.Constants
import com.baizan.daka.MyApp
import com.baizan.daka.util.SchedulerUtils
import com.hazz.kotlinmvp.net.BaseResponse
import com.hazz.kotlinmvp.net.RetrofitManager
import io.reactivex.Observable
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import top.zibin.luban.Luban
import java.io.File
import java.util.ArrayList

class UploadModel {

    fun upload(file: File): Observable<BaseResponse<String>> {
        return lubanCompressList(file.absolutePath)
            .flatMap { t ->
                val requestBody: RequestBody =
                    RequestBody.create(MediaType.parse("image/png"), t)
                val part =
                    MultipartBody.Part.createFormData("file", t.getName(), requestBody)
                RetrofitManager.service.upLoadFile(part)
            }.compose(SchedulerUtils.ioToMain())
    }

    fun upload(file: List<String>): Observable<BaseResponse<String>> {

        return lubanCompressList(file)
            .flatMap { t ->
                val requestBody: RequestBody =
                    RequestBody.create(MediaType.parse("image/png"), t)
                val part =
                    MultipartBody.Part.createFormData("file", t.getName(), requestBody)
                RetrofitManager.service.upLoadFile(part)
            }.compose(SchedulerUtils.ioToMain())
    }
//    fun upload(file: File): Observable<BaseResponse<String>> {
//        val requestBody: RequestBody = RequestBody.create(MediaType.parse("image/png"), file)
//        val part = MultipartBody.Part.createFormData("file", file.getName(), requestBody)
//        return RetrofitManager.service.upLoadFile(part)
//            .compose(SchedulerUtils.ioToMain())
//    }

    fun lubanCompressList(list: String): Observable<File> {
        try {
            val files = Luban.with(MyApp.instance)
                .load(list)
                .ignoreBy(100)
                .setTargetDir(Constants.DIR_PIC)[list]
            return Observable.just(files)
        } catch (e: Exception) {
            Log.e("luban", e.toString())
            return Observable.error(Throwable())
        }
    }

    fun lubanCompressList(list: List<String>): Observable<File> {
        val files = Luban.with(MyApp.instance)
            .load(list)
            .ignoreBy(100)
            .setTargetDir(Constants.DIR_PIC)
            .get()
        return Observable.fromIterable(files)
    }
}


